3-22 9. 回文数
Date:2022-03-22 07:36:03
标签:
反转一半数字算法
1002 % 10 = 2(取最后一位)
1002 / 10 = 100(右移一位)
类似题目:
- 125. 验证回文串 ( 简单😄 )
题目:9. 回文数 ( 简单😄 )
给你一个整数 x
,如果 x
是一个回文整数,返回 true
;否则,返回 false
。
回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
- 例如,
121
是回文,而123
不是。
示例
示例1:
输入:x = 121
输出:true
分析
该题和 回文串
类似
- 转化为字符串求解
- 不转化为字符串
由于整个过程我们不断将原始数字除以
10,然后给反转后的数字乘上
10,所以,当原始数字小于或等于反转后的数字时,就意味着我们已经处理了一半位数的数字了。
1221 % 10 = 1
1221 / 10 = 122 =>> 122 % 10 = 2
1 * 10 + 2 * 1 = 12 (此时原始数据12小于等于目前的12)
通过上述方法可以获取到反转一半后的值
题解
方法一:字符串+双指针法
function isPalindrome(x: number): boolean {
const numStr = x.toString()
let l = 0,
r = numStr.length - 1
while (l < r) {
if (numStr[l] !== numStr[r]) {
return false
}
++l
--r
}
return true
}
方法二:字符串+反转
function isPalindrome111(x: number): boolean {
const oldStr = x.toString()
const newStr = Array.from(oldStr).reverse().join('')
return oldStr == newStr
}
方法三:反转一半数字
function isPalindrome222(x: number): boolean {
// boundary
// 1.A negative number
// 2.0 is not in the end
if (x < 0) {
return false
}
// const len = x.toString().length
let ori = x,
curr = 0
// 1221
while (true) {
const tail = ori % 10
curr += tail
ori = Math.floor(ori / 10)
// 0 can not be in the end
if (curr == 0 && tail == 0) {
break
}
if (curr >= ori) {
break
}
curr *= 10
}
// if (len % 2 == 0) {
// return ori == curr
// } else {
// return ori == Math.floor(curr / 10)
// }
return ori == curr || ori == Math.floor(curr / 10)
}
使用
function main() {
const x = 121
// const x = -121
// const x = 10
// const x = 11
console.log('[]:', isPalindrome(x))
console.log('[]:', isPalindrome111(x))
console.log('[]:', isPalindrome222(x))
}
main()
export {}